//引入pinia
import { defineStore } from "pinia";
import { login } from "@/api/login";
import { ElMessage } from "element-plus";
import { ref } from "vue";

//创建store
export const userStore = defineStore(
  "localUser",
  () => {
    // 定义管理用户数据的state
    const id = ref(0);
    const username = ref("");
    const name = ref("");
    const token = ref("");
    const isLogin = ref(false);
    const avatar = ref("");

    // 定义获取接口数据的action函数
    const userLogin = async (data) => {
      //执行登录
      const result = await login(data);
      //登录成功
      if (result.code == 200) {
        id.value = result.data.userId;
        username.value = result.data.userName;
        name.value = result.data.nickName;
        isLogin.value = true;
        token.value = result.data.token;
        avatar.value = result.data.avatar;

        //信息提示
        ElMessage({
          showClose: true,
          message: "登录成功！",
          type: "success",
        });
      } else {
        //登录失败，提示错误信息
        ElMessage({
          showClose: true,
          message: "登录失败！",
          type: "error",
        });
      }
    };

    //登出方法
    const userLoginOut = () => {
      id.value = 0;
      name.value = "";
      username.value = "";
      isLogin.value = false;
      token.value = null;
    };

    // 以对象形式把state和action return
    return {
      id,
      username,
      name,
      userLogin,
      userLoginOut,
      token,
      isLogin,
      avatar,
    };
  },
  //持久化配置
  {
    persist: true,
  }
);
